﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Compression;
using System.IO;

namespace working
{
    public static class CompressUtil
    {
        public static void Compress(string targetzip, string rootDir, IEnumerable<string> rpaths)
        {
            if (System.IO.File.Exists(targetzip)){
                File.Delete(targetzip);
            }
            using (ZipStorer zip = ZipStorer.Create(targetzip))
            {
                foreach (var rpath in rpaths)
                {
                    var path = System.IO.Path.Combine(rootDir, rpath);
                    if (Directory.Exists(path))
                    {
                        var rdirPath = System.IO.Path.GetDirectoryName(rpath);
                        zip.AddDirectory(ZipStorer.Compression.Deflate, path, rdirPath);
                    }
                    else if(File.Exists(path))
                    {
                        zip.AddFile(ZipStorer.Compression.Deflate, path, rpath);
                    }
                }
            }
        }
        public static void UnCompress(string sourcezip,string targetFolder)
        {
            using (ZipStorer zip = ZipStorer.Open(sourcezip, FileAccess.Read))
            {
                var dirs = zip.ReadCentralDir();
                if (dirs.Count == 0)
                {
                    Console.WriteLine("dir count == 0");
                    return;
                }
                for (int i = 0; i < dirs.Count; i++)
                {
                    byte[] output = null;
                    var dir = dirs[i];
                    zip.ExtractFile(dir, out output);
                    if (output.Length == 0)
                    {
                        Console.WriteLine("output is empty!");
                        continue;
                    }

                    string filePath = System.IO.Path.Combine(targetFolder, dir.FilenameInZip);
                    string fileDir = System.IO.Path.GetDirectoryName(filePath);
                    if(!Directory.Exists(fileDir)) {
                        Directory.CreateDirectory(fileDir);
                    }
                    if(System.IO.File.Exists(filePath)){
                        System.IO.File.Delete(filePath);
                    }
                    System.IO.File.WriteAllBytes(filePath, output);
                }
            }
        }
    }
}
